package com.tiger.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tiger.utils.DateTimeUtils;
import com.tiger.mapper.base.*;
import com.tiger.mapper.homePage.HomePageErrorCardsMapper;
import com.tiger.mapper.homePage.HomePageQuestionCardsMapper;
import com.tiger.mapper.homePage.UserGoodWorksMapper;
import com.tiger.mapper.userAdminPage.UserWorksCountMapper;
import com.tiger.mapper.userHomePage.UserAchievementMapper;
import com.tiger.pojo.base.*;
import com.tiger.pojo.base.Error;
import com.tiger.pojo.homePage.HomePageErrorCards;
import com.tiger.pojo.homePage.HomePageQuestionCards;
import com.tiger.pojo.homePage.UserGoodWorks;
import com.tiger.pojo.userAdminPage.UserWorksCount;
import com.tiger.pojo.userHomePage.UserAchievement;
import com.tiger.pojo.userHomePage.UserData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * @author HuXuehao (StudiousTiger)
 * @desc 这个类的作用是
 * @date 2022/2/11
 */
@Slf4j
@RestController
public class UserHomePageForOtherController {
    @Autowired
    private ErrorMapper errorMapper;
    @Autowired
    private QuestionMapper questionMapper;
    @Autowired
    private BlinkMapper blinkMapper;
    @Autowired
    private InterestMapper interestMapper;
    @Autowired
    private UserAchievementMapper userAchievementMapper;
    @Autowired
    private UserGoodWorksMapper userGoodWorksMapper;
    @Autowired
    private UserWorksCountMapper userWorksCountMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private HomePageErrorCardsMapper homePageErrorCardsMapper;
    @Autowired
    private HomePageQuestionCardsMapper homePageQuestionCardsMapper;

    @Autowired
    private HttpServletRequest httpServletRequest;

    @RequestMapping(value = "/userHomePage/userWorksCount/{UID}", name = "根据用户id查询该用户的作品数量/user")
    public String getUserWorksCount(@PathVariable String UID){
        try {
            QueryWrapper<UserWorksCount> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id",UID);
            List<UserWorksCount> res = userWorksCountMapper.selectList(wrapper);
            if (res.size()>0){
                return JSON.toJSONString(res.get(0));
            } else {
                return "false";
            }
        } catch (Exception e) {
            log.error(e.toString());
            return "false";
        }

    }

    /**
     * 查找userHomePage上的用户的个人数据（TA的粉丝、TA的关注、TA的作品）
     * @param UID
     * @return
     */
    @RequestMapping(value = "/userHomePage/userData/{UID}", name = "查找用户主页-TA粉丝、TA的关注、TA的作品/user")
    public String getUserData(@PathVariable String UID){
        try {
            ArrayList<UserData> res = new ArrayList<>();
            // 粉丝数
            QueryWrapper<Interest> wrapper1 = new QueryWrapper<>();
            wrapper1.eq("interested_id",UID);
            Integer res1 = interestMapper.selectCount(wrapper1);
            res.add(new UserData("TA的粉丝",res1));
            // 关注数
            QueryWrapper<Interest> wrapper2 = new QueryWrapper<>();
            wrapper2.eq("interest_id",UID);
            Integer res2 = interestMapper.selectCount(wrapper2);
            res.add(new UserData("TA的关注",res2));
            // 作品数
            QueryWrapper<Error> wrapper3_1 = new QueryWrapper<>();
            wrapper3_1.eq("user_id",UID);
            Integer res3_1 = errorMapper.selectCount(wrapper3_1);
            //
            QueryWrapper<Question> wrapper3_2 = new QueryWrapper<>();
            wrapper3_2.eq("user_id",UID);
            Integer res3_2 = questionMapper.selectCount(wrapper3_2);
            //
            QueryWrapper<Blink> wrapper3_3 = new QueryWrapper<>();
            wrapper3_3.eq("user_id",UID);
            Integer res3_3 = blinkMapper.selectCount(wrapper3_3);
            //
            Integer res3 = res3_1 + res3_2 + res3_3;
            res.add(new UserData("TA的作品",res3));
            return JSON.toJSONString(res);
        } catch (Exception e) {
            log.error(e.toString());
            return "false";
        }
    }

    /**
     * 查找userHomePage上的用户的个人成就（被点赞、评论、收藏的次数）
     * @param UID
     * @return
     */
    @RequestMapping(value = "/userHomePage/userAchievement/{UID}", name = "查找用户主页-被点赞、评论、收藏的次数/user")
    public String getUserAchievement(@PathVariable String UID){
        try {
            QueryWrapper<UserAchievement> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id",UID);
            List<UserAchievement> res = userAchievementMapper.selectList(wrapper);
            if (res.size()>0){
                return JSON.toJSONString(res.get(0));
            } else {
                return "false";
            }
        } catch (Exception e) {
            log.error(e.toString());
            return "false";
        }
    }

    /**
     * 用户的优秀作品集锦
     * @param UID
     * @return
     */
    @RequestMapping(value = "/userHomePage/userGoodWorks/{UID}", name = "获取用户的优秀作品集锦/user")
    public String getUserGoodWorks(@PathVariable String UID){
        Page<UserGoodWorks> page = new Page<>(1, 9);
        QueryWrapper<UserGoodWorks> wrapper = new QueryWrapper<>();
        try {
            wrapper.eq("user_id",UID);
            Page<UserGoodWorks> userGoodWorksPage = userGoodWorksMapper.selectPage(page, wrapper);
            List<UserGoodWorks> res = userGoodWorksPage.getRecords();
            return JSON.toJSONString(res);
        } catch (Exception e) {
            log.error(e.toString());
            return "false";
        }

    }

    /**
     * 判断当前进入的个人主页是不是我自己
     * @param UID
     * @return
     */
    @RequestMapping(value = "/userHomePage/whetherMyself/{UID}", name = "判断当前个人主页是否是登录人的/user")
    public String whetherMyself(@PathVariable String UID){
        try {
            String userId = (String) httpServletRequest.getSession().getAttribute("userId");
            boolean res = UID.equals(userId);
            return res+"";
        } catch (Exception e) {
            log.error(e.toString());
            return "error";
        }
    }

    /**
     * 判断我是否关注了当前的UID的用户
     * @param UID
     * @return
     */
    @RequestMapping(value = "/userHomePage/whetherConcerned/{UID}", name = "判断我是否关注了当前的UID的用户/user")
    public String whetherConcerned(@PathVariable String UID){
        try {
            QueryWrapper<Interest> wrapper = new QueryWrapper<>();
            wrapper.eq("interest_id",httpServletRequest.getSession().getAttribute("userId"));
            wrapper.eq("interested_id",UID);
            List<Interest> res = interestMapper.selectList(wrapper);
            if (res.size()==1){
                return "true";
            } else {
                return "false";
            }
        } catch (Exception e) {
            log.error(e.toString());
            return "error";
        }

    }

    /**
     * 关注
     * @param UID 要被关注人的ID
     * @return
     */
    @RequestMapping(value = "/userHomePage/concerned/{UID}", name = "关注用户/user")
    public String concerned(@PathVariable String UID){
        Interest interest = new Interest();
        try {
            interest.setInterestId((String) httpServletRequest.getSession().getAttribute("userId"));
            interest.setInterestedId(UID);
            interest.setInterestDate(DateTimeUtils.currentDateTime2SQLTimestamp());
            int res = interestMapper.insert(interest);
            if (res == 1){
                return "true";
            }else {
                return "false";
            }
        } catch (Exception e) {
            log.error(e.toString());
            return "error";
        }
    }

    /**
     * 取消关注
     * @param UID 被关注人的ID
     * @return
     */
    @RequestMapping(value = "/userHomePage/cancelConcerned/{UID}", name = "取消关注用户/user")
    public String cancelConcerned(@PathVariable String UID){
        try {
            QueryWrapper<Interest> wrapper = new QueryWrapper<>();
            wrapper.eq("interest_id",httpServletRequest.getSession().getAttribute("userId"));
            wrapper.eq("interested_id",UID);
            int res = interestMapper.delete(wrapper);
            if (res == 1){
                return "true";
            }else {
                return "false";
            }
        } catch (Exception e) {
            log.error(e.toString());
            return "error";
        }


    }

    /**
     * 更新用户主页头部的背景
     * @param number 图片的序号
     * @return
     */
    @RequestMapping(value = "/userHomePage/changeHeadImg/{number}", name = "更新用户主页头部的背景/user")
    public String changeHeadImg(@PathVariable int number){
        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        try {
            updateWrapper.eq("user_id",httpServletRequest.getSession().getAttribute("userId"));
            updateWrapper.set("user_back_img_head_number",number);
            int res = userMapper.update(null,updateWrapper);
            if (res == 1) {
                return "true";
            } else {
                return "false";
            }
        } catch (Exception e) {
            log.error(e.toString());
            return "error";
        }
    }


    /**
     * 更新用户主页背景头部的背景
     * @param number 图片的序号
     * @return
     */
    @RequestMapping(value = "/userHomePage/changeBodyImg/{number}", name = "更新用户主页背景头部的背景/user")
    public String changeBodyImg(@PathVariable int number){
        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        try {
            updateWrapper.eq("user_id",httpServletRequest.getSession().getAttribute("userId"));
            updateWrapper.set("user_back_img_body_number",number);
            int res = userMapper.update(null,updateWrapper);
            if (res == 1) {
                return "true";
            } else {
                return "false";
            }
        } catch (Exception e) {
            log.error(e.toString());
            return "error";
        }
    }


    /**
     * 用户个人主页&用户管理端：根据UID查询Error (20个为一页)
     * @param UID
     * @return
     */
    @RequestMapping(value = "/userHomePage/error/query/{UID}/{currentPage}", name = "用户个人主页&用户管理端：根据UID查询Error/user")
    public String queryUserHomeError(@PathVariable String UID, @PathVariable int currentPage){
        Page<HomePageErrorCards> page = new Page<>(currentPage, 20);     // 分页，一页20个结果
        QueryWrapper<HomePageErrorCards> wrapper = new QueryWrapper<>();
        try {
            wrapper.eq("user_id",UID);
            wrapper.orderByDesc("publish_time");
            Page<HomePageErrorCards> pages = homePageErrorCardsMapper.selectPage(page, wrapper);
            List<HomePageErrorCards> res = pages.getRecords();
            if (res.size() == 0){
                return "empty";
            } else {
                return JSON.toJSONString(res);
            }
        } catch (Exception e) {
            log.error(e.toString());
            return "false";
        }
    }

    /**
     * 用户个人主页&用户管理端：根据UID查询Question (20个为一页)
     * @param UID
     * @return
     */
    @RequestMapping(value = "/userHomePage/question/query/{UID}/{currentPage}", name = "用户个人主页&用户管理端：根据UID查询Question/user")
    public String queryUserHomeQuestion(@PathVariable String UID, @PathVariable int currentPage){
        Page<HomePageQuestionCards> page = new Page<>(currentPage, 20);     // 分页，一页20个结果
        QueryWrapper<HomePageQuestionCards> wrapper = new QueryWrapper<>();
        try {
            wrapper.eq("user_id",UID);
            wrapper.orderByDesc("publish_time");
            Page<HomePageQuestionCards> pages = homePageQuestionCardsMapper.selectPage(page, wrapper);
            List<HomePageQuestionCards> res = pages.getRecords();
            if (res.size() == 0){
                return "empty";
            } else {
                return JSON.toJSONString(res);
            }
        } catch (Exception e) {
            log.error(e.toString());
            return "false";
        }
    }

    /**
     * 用户个人主页&用户管理端：根据UID查询Blink (20个为一页)
     * @param UID
     * @return
     */
    @RequestMapping(value = "/userHomePage/blink/query/{UID}/{currentPage}", name = "用户个人主页&用户管理端：根据UID查询Blink/user")
    public String queryUserHomeBlink(@PathVariable String UID, @PathVariable int currentPage){
        Page<Blink> page = new Page<>(currentPage, 20);     // 分页，一页20个结果
        QueryWrapper<Blink> wrapper = new QueryWrapper<>();
        try {
            wrapper.eq("user_id",UID);
            wrapper.eq("blink_tag",0);
            wrapper.orderByDesc("blink_date");
            Page<Blink> pages = blinkMapper.selectPage(page, wrapper);
            List<Blink> res = pages.getRecords();
            if (res.size() == 0){
                return "empty";
            } else {
                return JSON.toJSONString(res);
            }
        } catch (Exception e) {
            log.error(e.toString());
            return "false";
        }
    }

    /**
     * 获取分页数
     * @param classify
     * @param UID
     * @return
     */
    @RequestMapping(value = "/userHomePage/getPage/{classify}/{UID}", name = "获取用户主页相关内容的分页数/user")
    public Long getPages( @PathVariable String classify, @PathVariable String UID){
        if ("error".equals(classify)){
            Page<Error> page = new Page<>(1, 20);     // 分页，一页20个结果
            QueryWrapper<Error> wrapper = new QueryWrapper<>();
            try {
                wrapper.eq("user_id",UID);
                wrapper.eq("error_tag",0);
                Page<Error> pages = errorMapper.selectPage(page, wrapper);
                return pages.getPages();
            } catch (Exception e) {
                log.error(e.toString());
                return 0L;
            }
        } else if ("question".equals(classify)){
            Page<Question> page = new Page<>(1, 20);     // 分页，一页20个结果
            QueryWrapper<Question> wrapper = new QueryWrapper<>();
            try {
                wrapper.eq("user_id",UID);
                wrapper.eq("question_tag",0);
                Page<Question> pages = questionMapper.selectPage(page, wrapper);
                return pages.getPages();
            } catch (Exception e) {
                log.error(e.toString());
                return 0L;
            }
        } else {
            Page<Blink> page = new Page<>(1, 20);     // 分页，一页20个结果
            QueryWrapper<Blink> wrapper = new QueryWrapper<>();
            try {
                wrapper.eq("user_id",UID);
                wrapper.eq("blink_tag",0);
                Page<Blink> pages = blinkMapper.selectPage(page, wrapper);
                return pages.getPages();
            } catch (Exception e) {
                log.error(e.toString());
                return 0L;
            }
        }

    }


}
